package com.iwop.moto.utils.stringUtil;
import com.alibaba.fastjson.JSON;
import com.iwop.moto.model.FOrderPurchaseDetail;
import com.opslab.util.DateUtil;
import jxl.Sheet;
import jxl.Workbook;
import jxl.read.biff.BiffException;
import jxl.write.*;
import jxl.write.biff.RowsExceededException;
import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;

import java.io.*;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class StringUtils {
	/**
	 * 是否为空 空ture
	 * @param input
	 * @return
	 */
	public static boolean  isEmpty(String input){
        return !(input != null && input.trim().length() > 0);
    }
	public static boolean  isNotEmpty(String input){
        return input != null && input.trim().length() > 0;
    }
	
	public static boolean isNumber(String number)  
    {  
        Pattern pattern = Pattern.compile("[0-9]*");  
        Matcher matcher = pattern.matcher(number);
        return matcher.matches();
    }
	/** 
     * 手机号验证 
     *  
     * @param  str 
     * @return 验证通过返回true 
     */  
    public static boolean isMobile(String str) {   
        Pattern p = null;  
        Matcher m = null;  
        boolean b = false;
        String reg="^(((13[0-9])|(15([0-9]))|(18[0-9])|(14[5|7])|(17[([0-1])|3|([5-8])]))\\d{8})$";
        p = Pattern.compile(reg); // 验证手机号
        m = p.matcher(str);  
        b = m.matches();   
        return b;  
    } 
    /** 
     * 电话号码验证 
     *  
     * @param  str 
     * @return 验证通过返回true 
     */  
    public static boolean isPhone(String str) {   
        Pattern p1 = null,p2 = null;  
        Matcher m = null;  
        boolean b = false;    
        p1 = Pattern.compile("^[0][1-9]{2,3}-[0-9]{5,10}$");  // 验证带区号的  
        p2 = Pattern.compile("^[1-9]{1}[0-9]{5,8}$");         // 验证没有区号的  
        if(str.length() >9)  
        {   m = p1.matcher(str);  
            b = m.matches();    
        }else{  
            m = p2.matcher(str);  
            b = m.matches();   
        }    
        return b;  
    } 
    public static String buildUpper(String input){
		if(StringUtils.isEmpty(input))
			return "";
		return input.substring(0, 1).toUpperCase()+input.substring( 1);		
	}
	public static String buildLower(String input){
		if(StringUtils.isEmpty(input))
			return "";
		return input.substring(0, 1).toLowerCase()+input.substring( 1);		
	}
	public static boolean isEmail(String str){
		    Pattern p = null;  
	        Matcher m = null;  
	        boolean b = false;   
	        p = Pattern.compile("([0-9]{17}([0-9]|X))|([0-9]{15})"); // 验证身份证 
	        m = p.matcher(str);  
	        b = m.matches();   
	        return b;  
	}

    public static String repmobile(String mobile){
        StringBuffer sb  = new StringBuffer();
        for (int i = 0; i < mobile.length(); i++) {
            if (i == mobile.length()-11) {
                sb.append(mobile.charAt(i));
            } else if(i == mobile.length()-10) {
                sb.append(mobile.charAt(i));
            }else if(i == mobile.length()-9) {
                sb.append(mobile.charAt(i));
            }else if(i == mobile.length()-4) {
                sb.append(mobile.charAt(i));
            }else if(i == mobile.length()-3) {
                sb.append(mobile.charAt(i));
            }else if(i == mobile.length()-2) {
                sb.append(mobile.charAt(i));
            }else if(i == mobile.length()-1) {
                sb.append(mobile.charAt(i));
            }else {
                sb.append("*");
            }
        }
        return sb.toString();
    }

    public static String repname(String name){
        StringBuffer sb  = new StringBuffer();
        if(name.length() == 1 ){
            sb.append("*");
        } else if(name.length()==2){
            sb.append(name.charAt(0)).append("*");
        } else {
            for(int i = 0 ; i < name.length();i++ ){
                if( i > 0 && i < name.length()-1){
                    sb.append("*");
                } else {
                    sb.append(name.charAt(i));
                }
            }
        }
        return sb.toString();
    }

    private static double rad(double d)
    {
        return d * Math.PI / 180.0;
    }

    /**
     * 通过经纬度获取距离
     * */
    public static double GetDistance(double lat1, double lng1, double lat2, double lng2)
    {
        double radLat1 = rad(lat1);
        double radLat2 = rad(lat2);
        double a = radLat1 - radLat2;
        double b = rad(lng1) - rad(lng2);
        double s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) +
                Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math.sin(b / 2), 2)));
        s = s * 6378.137;
        s = Math.round(s * 10000) / 10000;
        return s;
    }

    public static String getWeek(Date date){
        String[] weekDaysName = { "0", "1", "2", "3", "4", "5", "6" };
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        int intWeek = calendar.get(Calendar.DAY_OF_WEEK) - 1;
        return weekDaysName[intWeek];
    }

    public static int getSafeInt(String str){
        try {
            return  Integer.parseInt(str);
        } catch (NumberFormatException e) {
            return 0;
        }
    }

    public static String getFirstSpell(String chinese) {
        StringBuffer pybf = new StringBuffer();
        char[] arr = chinese.toCharArray();
        HanyuPinyinOutputFormat defaultFormat = new HanyuPinyinOutputFormat();
        defaultFormat.setCaseType(HanyuPinyinCaseType.LOWERCASE);
        defaultFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
        for (int i = 0; i < arr.length; i++) {
            if (arr[i] > 128) {
                try {
                    String[] temp = PinyinHelper.toHanyuPinyinStringArray(arr[i], defaultFormat);
                    if (temp != null) {
                        pybf.append(temp[0].charAt(0));
                    }
                } catch (BadHanyuPinyinOutputFormatCombination e) {
                    e.printStackTrace();
                }
            } else {
                pybf.append(arr[i]);
            }
        }
        return pybf.toString().replaceAll("\\W", "").trim();
    }

    public static String getPromotionCode(String type ,String tel){
        if(type.equals("1")){
            return "R"+tel;
        }else if(type.equals("5")){
            return ""+tel;
        }else if (type.equals("popular")){
            return "U"+tel;
        }
        return null;
    }

    public static String getWeekOfDate(Date dt) {
        String[] weekDays = {"7", "1", "2", "3", "4", "5", "6"};
        Calendar cal = Calendar.getInstance();
        cal.setTime(dt);
        int w = cal.get(Calendar.DAY_OF_WEEK) - 1;
        if (w < 0)
            w = 0;
        return weekDays[w];
    }

    /**
     * 获取今天后的第几天
     * */
    public static Date getDateAfter(Date d, int day) {
        Calendar now = Calendar.getInstance();
        now.setTime(d);
        now.set(Calendar.DATE, now.get(Calendar.DATE) + day);
        return now.getTime();
    }

    public static int differentDays(Date date1,Date date2) {
        if(date1==null || date2==null){
            return 0;
        }
        Calendar cal1 = Calendar.getInstance();
        cal1.setTime(date1);
        Calendar cal2 = Calendar.getInstance();
        cal2.setTime(date2);
        int day1= cal1.get(Calendar.DAY_OF_YEAR);
        int day2 = cal2.get(Calendar.DAY_OF_YEAR);
        int year1 = cal1.get(Calendar.YEAR);
        int year2 = cal2.get(Calendar.YEAR);
        if(year1 != year2){ //同一年
            int timeDistance = 0 ;
            for(int i = year1 ; i < year2 ; i ++){
                if(i%4==0 && i%100!=0 || i%400==0){ //闰年
                    timeDistance += 366;
                }
                else{ //不是闰年
                    timeDistance += 365;
                }
            }
            return timeDistance + (day2-day1) ;
        }
        else{ //不同年
            return day2-day1;
        }
    }

    public static   void readUserExcel1(InputStream in,InputStream inputStream) throws BiffException, IOException {
        Workbook rwb = null;
        //获取Excel文件对象
        rwb = Workbook.getWorkbook(in);
        Workbook rwb1 = null;
        rwb1 = Workbook.getWorkbook(inputStream);
        //获取文件的指定工作表 默认的第一个
        Sheet sheet = rwb.getSheet(0);
        Sheet sheet1 = rwb1.getSheet(0);
        for(int i=0; i<sheet.getRows(); i++){
            boolean flag=true;
            String name = sheet.getCell(1, i).getContents()==null?"":sheet.getCell(1, i).getContents();
            for(int j=0; i<sheet1.getRows(); j++){
                String name1 = sheet1.getCell(1, i).getContents()==null?"":sheet1.getCell(1, i).getContents();
                if(name.equals(name1)){
                    flag=false;
                }
            }
            if(flag){
                System.out.println(name);
            }
        }
    }

    public static void writeExcel(OutputStream os, String[] title, List lists,String sheetName) throws IOException, WriteException {
        WritableFont wfc = new WritableFont(WritableFont.ARIAL,16,WritableFont.BOLD,false,jxl.format.UnderlineStyle.NO_UNDERLINE,jxl.format.Colour.RED);
        WritableCellFormat wcfFC = new WritableCellFormat(wfc);
        wcfFC.setBackground(jxl.format.Colour.BLUE);

        // 创建可以写入的Excel工作薄(默认运行生成的文件在tomcat/bin下 )
        WritableWorkbook wwb = Workbook.createWorkbook(os);
        // 生成工作表,(name:First Sheet,参数0表示这是第一页)
        WritableSheet sheet = wwb.createSheet(sheetName, 0);
        // 开始写入第一行(即标题栏)
        sheet.setColumnView(0,20);
        sheet.setColumnView(1,10);
        sheet.setColumnView(2,20);
        sheet.setColumnView(3,20);
        sheet.setColumnView(4,30);
        sheet.setColumnView(5,20);
        sheet.setColumnView(6,30);
        sheet.setColumnView(7,30);
        sheet.setColumnView(8,30);
        for (int i=0; i<title.length; i++) {
            // 用于写入文本内容到工作表中去
            Label label = null;
            // 在Label对象的构造中指明单元格位置(参数依次代表列数、行数、内容 )
            label = new Label(i, 0, title[i],wcfFC);

            // 将定义好的单元格添加到工作表中
            sheet.addCell(label);
        }
        // 开始写入内容
        for (int row=0; row<lists.size(); row++) {
            // 获取一条(一行)记录
            List list = (List) lists.get(row);
            // 数据是文本时(用label写入到工作表中)
            for (int col=0; col<list.size(); col++) {
                String listvalue = (String)list.get(col);
                Label label = null;
                label = new Label(col, row+1, listvalue);
                sheet.addCell(label);
            }
        }

        // 写入数据
        wwb.write();
        // 关闭文件
        wwb.close();
        // 关闭输出流
        os.close();
    }

    /**
     * 后台管理导出审核通过记录 格式为对私批量代付格式
     *
     */
    public static void saveExcel(OutputStream os, String[] title, List lists,String sheetName) throws IOException, WriteException {
        WritableFont wfc = new WritableFont(WritableFont.ARIAL,16,WritableFont.BOLD,false,jxl.format.UnderlineStyle.NO_UNDERLINE,jxl.format.Colour.RED);
        WritableCellFormat wcfFC = new WritableCellFormat(wfc);
        wcfFC.setBackground(jxl.format.Colour.GREY_25_PERCENT);

        // 创建可以写入的Excel工作薄(默认运行生成的文件在tomcat/bin下 )
        WritableWorkbook wwb = Workbook.createWorkbook(os);
        // 生成工作表,(name:First Sheet,参数0表示这是第一页)
        WritableSheet sheet = wwb.createSheet(sheetName, 0);

        // 开始写入第一行(即标题栏)
        sheet.setColumnView(0,20);
        sheet.setColumnView(1,20);
        sheet.setColumnView(2,20);
        sheet.setColumnView(3,30);
        sheet.setColumnView(4,50);
        sheet.setColumnView(5,20);

        for (int i=0; i<title.length; i++) {
            // 用于写入文本内容到工作表中去
            Label label = null;
            // 在Label对象的构造中指明单元格位置(参数依次代表列数、行数、内容 )
            label = new Label(i, 0, title[i],wcfFC);
            // 将定义好的单元格添加到工作表中
            sheet.addCell(label);
        }
        // 开始写入内容
        for (int row=0; row<lists.size(); row++) {
            // 获取一条(一行)记录
            List list = (List) lists.get(row);
            // 数据是文本时(用label写入到工作表中)
            for (int col=0; col<list.size(); col++) {
                {
                    if(list.get(col) instanceof String)
                    {
                        String listvalue = (String) list.get(col);
                        Label label = null;
                        label = new Label(col, row + 1, listvalue);
                        sheet.addCell(label);
                    }else if (list.get(col) instanceof BigDecimal){
                        double listvalue =0.00;
                        listvalue = ((BigDecimal) list.get(col)).doubleValue();
                        jxl.write.Number labelnum = new jxl.write.Number(col, row + 1, listvalue);
                        sheet.addCell(labelnum);
                    }else{
                        String listvalue = (String) list.get(col);
                        Label label = null;
                        label = new Label(col, row + 1, listvalue);
                        sheet.addCell(label);
                    }
                }
            }
        }

        // 写入数据
        wwb.write();
        // 关闭文件
        wwb.close();
        // 关闭输出流
        os.close();
    }

    public static void main(String[] args) {
        Calendar   cal   =   Calendar.getInstance();
        cal.add(Calendar.DATE,   -10);
        Date time = cal.getTime();
        System.out.println(time);
        String yesterday = new SimpleDateFormat( "yyyy-MM-dd ").format(cal.getTime());
        System.out.println(yesterday);
    }
}
